<template>
  <el-dialog :visible.sync="dialogVisible" title="修改未通过审核的提问" width="30%" style="min-width: 400px;" @open="onDialogOpen">
    <div style="display: flex; flex-direction: column; justify-content: left; align-items: left;">
      <div v-if="questions.length > 0">
        <div style="display: flex; align-items: center; margin-top: 10px;">
          <div style="margin-right: 10px;">向<b>{{questions[currentPage].answered_by.username}}</b>提问，未通过<b>{{questions[currentPage].rejected_by.username}}</b>审核</div>
        </div>
        <div style="text-align: left;">请修改你的问题：</div>
        <el-input type="textarea" v-model="questions[currentPage].content" :rows="4" placeholder="请输入问题内容(至少10个字)"></el-input>
      </div>
      <div v-else>
        <el-text class="mx-1">没有未通过审核的问题</el-text>
      </div>
    </div>
    <div slot="footer" class="dialog-footer" style="text-align: center; margin-top: 10px;">
      <el-button @click="emits('editQuestion-canceled')">取消</el-button>
      <el-button v-if="questions.length > 0" type="primary" @click="onSubmit" :disabled="questions[currentPage].content.length <= 10">提交</el-button>
      <el-button v-if="questions.length > 0" type="primary" @click="onDelete">删除</el-button>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue';
import { createQuestion, loadQuestionsRejected, editQuestion, deleteQuestion } from '../utils/apiQuestion'
import { ElMessage } from 'element-plus';
import { myUserInfo } from '../utils/apiUser.js'

const dialogVisible = ref(false);
const currentPage = ref(0);
const total = ref(5)
const questions = ref([]);

const loadQuestions = () => {
  loadQuestionsRejected(myUserInfo().id).then(res => {
    questions.value = res.data
    total.value = res.data.length
    currentPage.value = 0
    if (total.value <= currentPage.value) {
      currentPage.value = 0
    }
  }).catch(error => {
  })
}

const onDialogOpen = () => {
  loadQuestions()
}

const onDelete = () => {
  deleteQuestion(questions.value[currentPage.value].id).then(res=>{
    loadQuestions()
    ElMessage.success('删除问题成功！')
  })
}

const onSubmit = () => {
  editQuestion(questions.value[currentPage.value].id, questions.value[currentPage.value].content).then(res=>{
    loadQuestions()
    ElMessage.success('编辑问题成功！')
  }).catch(error => {
    ElMessage.error('提问失败')
  })
}

const emits = defineEmits(['editQuestion-canceled'])

</script>
